<?PHP

require_once($CFG->libdir .'/phpxml/xml.php');
require_once($CFG->libdir .'/filelib.php');
require_once($CFG->dirroot."/blocks/widget_store/framework/WookieConnectorService.php");
 

class block_widget_store extends block_base {
	

    function init() {
        $this->version = 201232800;
        $this->title = 'Widget Store';
        $this->content_type = BLOCK_TYPE_TEXT;
    }
    
    function has_config(){
        return true;
    }
    
    function instance_allow_config() {
        return true;
    }
    
    function applicable_formats() {
        return array('all' => true);
    }

    /**
    * Widgets actually look nicer without the header, but
    * it means they can't be dragged around when using ajaxy
    * Moodle themes. 
    */
    function hide_header() {
        return false;
    }
    
	function get_content() { 
		if($this->content !== NULL) {
            return $this->content;
        }
        $this->content = new stdClass; 
        if (!$this->config->widget_url && $this->config->widget_id){ 
            $this->instantiateWidget(); 
        } 
        if (!$this->config->widget_url){ 
            $this->content->text = get_string('configurewidget','block_widget_store'); 
        } else { 
            // Render output
            $this->content->text = '<iframe style="border:none" src="'.$this->config->widget_url.'" height="'.$this->config->widget_height.'" width="'.$this->config->widget_width.'"></iframe>';
            // Show embed code - comment this line out if you want
            // to disable embedding
            $this->content->footer = $this->get_embed_code();       
        }
        return $this->content;
    }
    
    function get_embed_code(){
        global $CFG;
        $embedtext = '&lt;iframe style="border:none" src="'.$this->config->widget_url.'" height="'.$this->config->widget_height.'" width="'.$this->config->widget_width.'"&gt;&lt;/iframe&gt;';
        $text = '<a href="#" onclick="document.getElementById('."'embed_".$this->instance->id."'".').style.display='."'block'".'"><img src="'.$CFG->wwwroot.'/blocks/widget_store/embed.png" alt="get embed code"/></a>';
        $text = $text.'<div id="embed_'.$this->instance->id.'"  style="display:none">';
        $text = $text.'copy the text below into your page:<br/>';
        $text = $text.'<textarea style="width:100%;height:100px">'.$embedtext.'</textarea>';
        $text = $text.'<a href="#" onclick="document.getElementById('."'embed_".$this->instance->id."'".').style.display='."'none'".'">hide embed code</a></div>';
        return $text;
    }
    

 	function specialization() { 
        if ($this->config){ 
            if ($this->config->widget_id) $this->instantiateWidget(); 
        	$this->title = $this->config->widget_title; 
        } 
    }
    
    function instance_allow_multiple() {
        return true;
    }
    
    // Unfortunately, called before we know the widget's actual width
    function preferred_width(){
        return 320;
    }
    
    /**
     * Sets up a widget instance
     */
    function instantiateWidget(){
        global $USER, $CFG, $COURSE;
        $w_url = (string)$CFG->block_widget_store_url;
        $w_key = (string)$CFG->block_widget_store_key;
		$fullname = "Guest";
		$username = "Guest";
		if ( !empty($USER->username) ) {
			$fullname = $USER->firstname." ".$USER->lastname;
			$username = $USER->username;
		}
        $conn = new WookieConnectorService ($w_url, $w_key, $this->instance->id, $username, $fullname );
        $widgetInstance = $this->getWidget($conn);  
        $context = get_context_instance(CONTEXT_BLOCK, $this->instance->id);      
        // Set defaults
		if ( $widgetInstance ) {
			$this->setProperty($widgetInstance, "username", $username, $conn);
			$site_context = get_system_context();
			$this->setProperty($widgetInstance, "administrator", "false", $conn);
			if (has_capability('moodle/site:doanything', $site_context )) {
				$this->setProperty($widgetInstance, "manager", "true", $conn );
			}
			else {
				$this->setProperty($widgetInstance, "manager", "false", $conn );
			}
        	if (has_capability('moodle/course:manageactivities', $context )) {
        	    $this->setProperty($widgetInstance, "moderator", "true", $conn);
        	}
			//print_object($this);
			
			
			
        	// Add participant
        	$this->addParticipant($widgetInstance, $conn);
		}
    }
    
    /**
     * Obtains a Widget instance
     * NOTE that this should in future call the REST API using POST
     * but this is currently tricky with Moodle's download_file_content function
     */
    function getWidget($connection){
        global $USER, $COURSE, $CFG;

        $widget = $connection->getOrCreateInstance ( $this->config->widget_id );
		if ( $widget ) {
	        
	        $this->config->widget_url =$widget->getURL();
	        $this->config->widget_height = $widget->getHeight();
	        $this->config->widget_width = $widget->getWidth();
	        $this->config->widget_title = $widget->getTitle();
	        $this->title = $this->config->widget_title;
	        $this->instance_config_commit();
	        $this->refresh_content();
		}
		return $widget;
    }
    
    /**
     * Sets a Personal Property for a Widget instance
     * NOTE that this should in future call the REST API using POST
     * but this is currently tricky with Moodle's download_file_content function
     */
    function setProperty($widgetInstance, $key,$value, $connection){
        global $USER, $COURSE,$CFG;

		$newProperty = new Property ( $key, $value );
		$r = $connection->setProperty ( $widgetInstance, $newProperty );
    }
    
    /**
     * Adds a participant
     * NOTE that this should in future call the REST API using POST
     * but this is currently tricky with Moodle's download_file_content function
     */
     function addParticipant($widgetinstance, $connection){
        global $USER, $COURSE, $CFG;
        
        if ($USER->picture != ""){
            $src = $CFG->httpswwwroot.'/user/pix.php/'.$USER->id.'/f1.jpg';
        } else {
            $src = $CFG->httpswwwroot.'/pix/u/f1.png';
        }
		$thisUser = null;
		if ( !empty($USER->username)) {
        	$fullname = $USER->firstname.' '.$USER->lastname;
        	$thisUser = new User ( $USER->username, $fullname, $src );
		}
		else {
			$thisUser = new User ( "Guest", "Guest", $src);
		}
        $connection->addParticipant($widgetinstance, $thisUser );

     }
}



/**
 * Gallery support class
 */
class widget_gallery {

    function init(){ 
    }

    function showGallery(){
    	global $USER,$CFG;

		$instanceID = required_param('instanceid');
        $gallery = "<div id=\"widget_gallery\" class=\"widget-gallery\">";
        $conn = new WookieConnectorService ($CFG->block_widget_store_url, $CFG->block_widget_store_key, $instanceID, $USER->username );
	
        $widgets = $conn->getAvailableWidgets();
        
		
		foreach ($widgets as $widget){ 
            $gallery = $gallery."
                <div class=\"wookie-widget\">
                    <div class=\"wookie-icon-area\"><img class=\"wookie-icon\" src=\"".$widget->getIcon()."\" width=\"75\" height=\"75\"/></div>
                      <div class=\"wookie-title\">".$widget->getTitle()."</div>
                      <div class=\"wookie-description\">".$widget->getDescription()."</div>
                      <div class=\"wookie-choose\"><input type=\"button\" class=\"wookie-button\" value=\"select widget\" id=\"".$widget->getIdentifier()."\"></div>
                </div>
            ";
        }
        $gallery = $gallery."</div><br/>";
        return $gallery;
    }
    
}
?>